
from ding_robot import DingRobot
from cal_data import CalculateData
from txt_to_dict import txt_to_dict
import sys, logging, time
from pathlib import Path
from datetime import date, timedelta

logging.basicConfig(
    format = "%(asctime)s %(levelname)s:%(name)s: %(message)s",
    level = logging.INFO,
    datefmt = "%H:%M:%S",
    stream = sys.stderr
)
logger = logging.getLogger(__name__)


class DailyReport(DingRobot, CalculateData):

    def __init__(self, webhooks: list, secrets: list, main_path, source_name, project_name, title) -> None:
        DingRobot.__init__(self, webhooks, secrets)
        CalculateData.__init__(self, main_path, source_name)
        self._project_name = project_name
        self._title = title
        self._now_date = date.today()

    
    # 创建发送的信息文字
    def gen_message(self):
        self._title = f"{self._title}"
        self._text = f"### **{self._now_date}** *{self._project_name}{self._title}* \n" \
        f"截至{self._date_max_str[5:]}，测试第{(self._date_max-self._date_min).days+1}天;\n"
        # 生成累计文字
        if self._date_min < self._date_max:
            self._text += f"#### **累计数据：**\n" \
            f"- 累计花费${self._cum_spend if self._cum_spend else 0: .0f}，" \
            f"成本${self._cum_spend/self._cum_num_dev: .2f}，" \
            f"量级{self._cum_num_dev: .0f}; \n" \
            f"- 累计完整次留率{self._cum_num_retent_before_yesterday/self._cum_num_dev_before_yesterday if self._cum_num_dev_before_yesterday else 0: .2%}，" \
            f"完整三留率{self._cum_num_d3_retent/self._cum_num_dev_before_2day if self._cum_num_dev_before_2day else 0: .2%}; \n" \
            f"- 累计首日付费率{self._cum_d1_rech_ndev/self._cum_num_dev if self._cum_num_dev else 0: .2%}，" \
            f"首日ROI{self._cum_d1_price/self._cum_spend if self._cum_spend else 0: .2%}; \n"
        if self._date_min < self._date_max - timedelta(days=1):
            self._text += f"- 累计完整三日付费率{self._cum_d3_rech_ndev/self._cum_num_dev_before_2day if self._cum_num_dev_before_2day else 0: .2%}，" \
            f"完整三日ROI{self._cum_d3_price/self._cum_spend_before_2day if self._cum_spend_before_2day else 0: .2%}; \n"
        # 生成昨日文字
        self._text += f"#### **昨日数据：**\n" \
            f"- 昨日花费${self._spend if self._spend else 0: .1f}，" \
            f"成本${self._spend/self._num_dev if self._num_dev else 0: .2f}，" \
            f"量级{self._num_dev if self._num_dev else 0: .0f}; \n" \
            f"- 昨日点击率{self._clicks/self._impressions if self._impressions else 0: .2%}，" \
            f"转化率{self._installs/self._clicks if self._clicks else 0: .2%}，" \
            f"注册率{self._num_login/self._num_dev if self._num_dev else 0: .2%}，" \
            f"新手引导完成率{self._num_tutor/self._num_dev if self._num_dev else 0: .2%}; \n"
        if self._date_min < self._date_max:
            self._text += f"- 前日次留率{self._num_retent_before_yesterday/self._num_dev_before_yesterday if self._num_dev_before_yesterday else 0: .2%}; \n"
        self._text += f"#### **分日花费与留存数据：**\n"
        self._text += "\n"
        if not self._df_group_daily_format.empty:
            self._df_group_daily_format.rename(columns={
                "dates":"日期", "spending":"花费", "num_dev":"量级", "CPI":"成本", "rate_clicks":"点击", "rate_installs":"转化", 
                "rate_login":"注册", "rate_tutor":"新完", "rate_retent":"次留", "rate_d3_retent":"三留","rate_d1_rech":"首付",
                "ROI_d1":"首ROI","rate_d3_rech":"三付","ROI_d3":"三ROI","ratio_d3_rech_retent":"三付留比"
                }, inplace=True)
            self._text += self._df_group_daily_format[['日期','花费','量级','成本','新完','次留','三留']].to_markdown(index=False)
            self._text += "\n"
            self._text += f"#### **分日付费与留存比数据：**\n"
            self._text += "\n"
            self._text += self._df_group_daily_format[['日期','首付','首ROI','三付','三ROI','三付留比']].to_markdown(index=False)

    def run(self):
        self.read_source()
        source_data = self.drop_columns()
        self.group_by_date(source_data['daily'])
        self.cal_yesterday_data()
        if self._date_min < self._date_max:
            self.cal_cum_data()
        self.cal_daily_data()
        # self.gen_message()
        self.to_ding_talk()


def main():
    s0 = time.perf_counter()
    project_name = 'test'
    title = '第六轮测试'
    main_path = Path(__file__).resolve().parent
    source_name = 'GS_shark'
    access_token_path = main_path.joinpath('数据源', 'access_tokens.txt')
    secret_path = main_path.joinpath('数据源', 'secrets.txt')
    access_tokens = txt_to_dict(access_token_path)
    webhooks = ["https://oapi.dingtalk.com/robot/send?access_token=" + access_token for access_token in access_tokens[project_name]]
    secrets = txt_to_dict(secret_path)
    if webhooks and secrets:
        daily_report = DailyReport(webhooks, secrets[project_name], main_path, source_name, project_name, title)
        daily_report.run()
    logger.info(f'总用时{time.perf_counter() - s0: .2f}秒.')
    # print(daily_report.text)


if __name__ == '__main__':
    main()

